package com.sky.task;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.http.WebSocket;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 每分钟处理一次超时订单
     */
    @Scheduled(cron = "0 * * * * *")
//    @Scheduled(cron = "1/5 * * * * *") 测试用
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        //查询待付款订单 下单时间超过15分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        //自动取消订单
        if(ordersList != null && ordersList.size() > 0){
            for (Orders order:ordersList){
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时自动取消");
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * *")测试用
    public void processDeliveryOrder(){
        log.info("处理一直处于派送中的订单");
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);
        //自动完成订单
        if(ordersList != null && ordersList.size() > 0){
            for (Orders order:ordersList){
                order.setStatus(Orders.COMPLETED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单在 1:00 自动完成");
                orderMapper.update(order);
            }
        }
    }
}
